<?php

namespace app\components;

use app\models\Admin;
use app\models\OauthClient;
use app\models\User;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ServerRequest;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\ResourceServer;
use Yii;
use app\components\oauth2\repositories\AccessTokenRepository;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\CryptKey;
use yii\di\Instance;
use yii\web\ForbiddenHttpException;

class ResourceServerInstance
{
    /** @var ResourceServer */
    public $server;

    public function __construct($server)
    {
        $this->server = $server;
    }

    /**
     * @return AuthorizationServer
     * @throws \yii\base\InvalidConfigException
     */
    public static function getTotal()
    {
        if (!Yii::$container->has(self::class)) {
            // Init our repositories
            $accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface

// Path to authorization server's public key
            $publicKeyPath = new CryptKey(\Yii::$app->getBasePath() . \Yii::$app->params['oauth2']['public_key_path'], null, false);

// Setup the authorization server
            $server = new ResourceServer(
                $accessTokenRepository,
                $publicKeyPath
            );
            Yii::$container->setSingleton(self::class, [
                'class' => self::class,
                'server' => $server
            ]);
        }
        /** @var  $instance self */
        $instance = Instance::ensure(self::class);
        return $instance->server;
    }

    public function set($new_val)
    {
        $this->server = $new_val;
        return $this;
    }

    public static function getUser(){
        $server = self::getTotal();

        $serverRequest = ServerRequest::fromGlobals();
        $response = new Response();

        try {
            $authRequest = $server->validateAuthenticatedRequest($serverRequest);
        }catch (OAuthServerException $e){
            throw new ForbiddenHttpException();
        }



        $keys = ['oauth_access_token_id', 'oauth_client_id', 'oauth_user_id', 'oauth_scopes'];

        $client_id = $authRequest->getAttribute('oauth_client_id');

        $user_id = $authRequest->getAttribute('oauth_user_id');

        $client = OauthClient::find()->where(['=','client_id',$client_id])->one();

        $user = null;

        if($client){
            $user = $client->getEntity();

            if ($user == null) {//用户找不到,判断是前端用户还是后台
                if ($client->client_user_type == OauthClient::TYPE_BACKGROUND) {
                    $user = Admin::findOne($user_id);
                } else if ($client->client_user_type == OauthClient::TYPE_FRONTAND) {
                    $user = User::findOne($user_id);
                }
            }
        }

        return $user;
    }
}
